package io.renren.modules.practice.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.ShiroUtils;
import io.renren.modules.practice.dao.PythonQuizDao;
import io.renren.modules.practice.dao.StudentPythonSubmitDao;
import io.renren.modules.practice.entity.PythonQuizEntity;
import io.renren.modules.practice.entity.StudentPythonSubmitEntity;
import io.renren.modules.practice.entity.dto.PythonSubmitDto;
import io.renren.modules.practice.service.PythonPracticeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Slf4j
@Service
public class PythonPracticeServiceImpl extends ServiceImpl<PythonQuizDao, PythonQuizEntity> implements PythonPracticeService {

    @Autowired
    private StudentPythonSubmitDao studentPythonSubmitDao;

    @Override
    public java.util.List<PythonQuizEntity> getQuizListByChapterId(Integer chapterId) {
        return baseMapper.selectByChapterId(chapterId);
    }

    @Override
    public PythonQuizEntity getQuizById(Integer quizId) {
        return baseMapper.selectById(quizId);
    }

    @Override
    public boolean submitPythonAnswer(PythonSubmitDto submitDto) {
        try {
            // 获取题目信息
            PythonQuizEntity quiz = baseMapper.selectById(submitDto.getQuizId());
            if (quiz == null) {
                log.error("题目不存在: {}", submitDto.getQuizId());
                return false;
            }

            // 判断答案是否正确
            boolean isCorrect = quiz.getCorrectAnswer().equals(submitDto.getSelectedAnswer());

            // 保存提交记录
            StudentPythonSubmitEntity submitEntity = new StudentPythonSubmitEntity();
            submitEntity.setUserId(ShiroUtils.getUserId().intValue());
            submitEntity.setQuizId(submitDto.getQuizId());
            submitEntity.setSelectedAnswer(submitDto.getSelectedAnswer());
            submitEntity.setIsCorrect(isCorrect);
            submitEntity.setSubmitTime(new Date());

            studentPythonSubmitDao.insert(submitEntity);

            return isCorrect;

        } catch (Exception e) {
            log.error("Python基础题目提交异常: {}", e.getMessage(), e);
            return false;
        }
    }
} 